package com.letianpai.utils;

import java.io.ByteArrayInputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.CallLog;
import android.provider.ContactsContract;
import android.util.Log;

import com.letianpai.bean.UserCallLog;

public class CallUtils {
	/*
	 * 获取通话记录
	 */
	public static List<UserCallLog> getCallLog(Context context) {
		List<UserCallLog> callList = new ArrayList<UserCallLog>();
		ContentResolver cr;
		Cursor cursor = null;
		Cursor cursor2 = null;
		Cursor cursor3 = null;
		String phot_ID = null;
		int i = 0;
		cr = context.getContentResolver();
		cursor = (cr.query(CallLog.Calls.CONTENT_URI,// 使用系统URI，取得通话记录

				new String[] { CallLog.Calls.NUMBER,// 电话号码

						CallLog.Calls.CACHED_NAME,// 联系人

						CallLog.Calls.TYPE,// 通话类型

						CallLog.Calls.DATE,// 通话时间

						CallLog.Calls.DURATION, // 通话时长
						CallLog.Calls._ID

				}, null, null, CallLog.Calls.DEFAULT_SORT_ORDER));

		// 遍历每条通话记录
		for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
			UserCallLog ucl = new UserCallLog();
			String strNumber = cursor.getString(0); // 呼叫号码
			String strName = cursor.getString(1); // 联系人姓名

			int type = cursor.getInt(2);
			int userId = cursor.getInt(5);
			String duration = getStandardTime(cursor.getLong(4));
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

			Date date = new Date(Long.parseLong(cursor.getString(3)));
			
			String time = sdf.format(date).substring(0, 6);
			if (null != strName) {
				Uri uri = Uri
						.parse("content://com.android.contacts/data/phones/filter/"
								+ strName);
				cursor2 = cr.query(uri, new String[] { "photo_id" }, null,
						null, null);

				if (cursor2.moveToFirst()) {

					phot_ID = cursor2.getString(0);
					if (null != phot_ID) {
						cursor3 = cr.query(ContactsContract.Data.CONTENT_URI,
								new String[] { "data15" },
								"ContactsContract.Data._ID=" + phot_ID, null,
								null);

						if (cursor3.moveToFirst()) {
							byte[] photoicon = cursor3.getBlob(0);

							ByteArrayInputStream inputStream = new ByteArrayInputStream(
									photoicon);

							Bitmap contactPhoto = BitmapFactory
									.decodeStream(inputStream);
							ucl.setPhoto(contactPhoto);
						}
						cursor3.close();
					}

				}
				cursor2.close();
			}
			ucl.setUserId(userId);
			ucl.setPhotoId(phot_ID);
			ucl.setUserName(strName);
			ucl.setPhoneNum(strNumber);
			ucl.setConverseTime(time);
			ucl.setCallType(type);
			ucl.setDuration(duration);
			callList.add(ucl);
			i++;

		}
		cursor.close();
		return callList;
	}

	/*
	 * 换成00:00:00格式时间
	 */
	public static String getStandardTime(long timestamp) {
		SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss",
				Locale.getDefault());
		sdf.setTimeZone(TimeZone.getTimeZone("GMT+0"));
		Date date1 = new Date(timestamp * 1000);
		sdf.format(date1);
		return sdf.format(date1);
	}

	/*
	 * 根据图片id获取图片
	 */

	public static Bitmap getBitmap(String photoId, Context context) {
		ContentResolver cr = context.getContentResolver();
		Bitmap contactPhoto = null;
		if (null != photoId) {
			Cursor cursor = cr.query(ContactsContract.Data.CONTENT_URI,
					new String[] { "data15" }, "ContactsContract.Data._ID="
							+ photoId, null, null);

			if (cursor.moveToFirst()) {

				byte[] photoicon = cursor.getBlob(0);

				ByteArrayInputStream inputStream = new ByteArrayInputStream(
						photoicon);

				contactPhoto = BitmapFactory.decodeStream(inputStream);
			}
			cursor.close();
		}

		return contactPhoto;
	}

	/*
	 * 查询联系人的通话记录(按电话号码查询)
	 */
	public static List<UserCallLog> getPersonCallLog(Context context,
			String number) {
		ContentResolver resolver = context.getContentResolver();
		List<UserCallLog> list = new ArrayList<UserCallLog>();
		Cursor cursor = resolver.query(CallLog.Calls.CONTENT_URI, new String[] {

		CallLog.Calls.CACHED_NAME,// 联系人

				CallLog.Calls.TYPE,// 通话类型

				CallLog.Calls.DATE,// 通话时间


				CallLog.Calls.DURATION, // 通话时长

		}, "number=?", new String[] { number },
				CallLog.Calls.DEFAULT_SORT_ORDER);
		cursor.moveToFirst();
		for (int i = 0; i < cursor.getCount(); i++) {

			UserCallLog ucl = new UserCallLog();
			String name = cursor.getString(0);
			int type = cursor.getInt(1);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");

			Date date = new Date(Long.parseLong(cursor.getString(2)));
			String time = sdf.format(date);
			String duration = getStandardTime(cursor.getLong(3));
			ucl.setPhoneNum(number);
			ucl.setCallType(type);
			ucl.setDuration(duration);
			ucl.setConverseTime(time);
			ucl.setUserName(name);
			list.add(ucl);
			cursor.moveToNext();
		}
		cursor.close();
		return list;
	}

	
	/*
	 * 删除通话记录
	 */
	public static void delete(Context context, List<Integer> useridList) {
		ContentResolver resolver = context.getContentResolver();
		for (int i = 0; i < useridList.size(); i++) {
			resolver.delete(CallLog.Calls.CONTENT_URI, "_id=?",
					new String[] { useridList.get(i) + "" });
		}
	}

	/*
	 * 根据条数查询通话记录
	 */
	public static List<UserCallLog> etCallLog(Context context, int firstItem,
			int lastItem) {
		List<UserCallLog> callList = new ArrayList<UserCallLog>();
		ContentResolver cr;
		Cursor cursor = null;
		Cursor cursor2 = null;
		Cursor cursor3 = null;
		String phot_ID = null;
		cr = context.getContentResolver();
		cursor = (cr.query(CallLog.Calls.CONTENT_URI,// 使用系统URI，取得通话记录

				new String[] { CallLog.Calls.NUMBER,// 电话号码

						CallLog.Calls.CACHED_NAME,// 联系人

						CallLog.Calls.TYPE,// 通话类型

						CallLog.Calls.DATE,// 通话时间

						CallLog.Calls.DURATION, // 通话时长
						CallLog.Calls._ID

				}, null, null, CallLog.Calls.DEFAULT_SORT_ORDER));
		int sum = cursor.getCount();
		// 遍历每条通话记录
		for (cursor.moveToPosition(firstItem); !cursor.isAfterLast()
				&& firstItem < lastItem; cursor.moveToNext()) {
			UserCallLog ucl = new UserCallLog();
			Log.d("zzzz", "越界");
			String strNumber = cursor.getString(0); // 呼叫号码
			String strName = cursor.getString(1); // 联系人姓名
			int type = cursor.getInt(2);
			int userId = cursor.getInt(5);
			String duration = getStandardTime(cursor.getLong(4));
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

			Date date = new Date(Long.parseLong(cursor.getString(3)));
			String time = sdf.format(date).substring(5, 10);
			if (null != strName) {
				Uri uri = Uri
						.parse("content://com.android.contacts/data/phones/filter/"
								+ strName);
				cursor2 = cr.query(uri, new String[] { "photo_id" }, null,
						null, null);

				if (cursor2.moveToFirst()) {

					phot_ID = cursor2.getString(0);
					if (null != phot_ID) {
						cursor3 = cr.query(ContactsContract.Data.CONTENT_URI,
								new String[] { "data15" },
								"ContactsContract.Data._ID=" + phot_ID, null,
								null);

						if (cursor3.moveToFirst()) {
							byte[] photoicon = cursor3.getBlob(0);

							ByteArrayInputStream inputStream = new ByteArrayInputStream(
									photoicon);

							Bitmap contactPhoto = BitmapFactory
									.decodeStream(inputStream);
							ucl.setPhoto(contactPhoto);

						}
						cursor3.close();
					}

				}
				cursor2.close();
			}
			ucl.setUserId(userId);
			ucl.setPhotoId(phot_ID);
			ucl.setUserName(strName);
			ucl.setPhoneNum(strNumber);
			ucl.setConverseTime(time);
			ucl.setCallType(type);
			ucl.setDuration(duration);
			callList.add(ucl);
			firstItem++;

		}
		cursor.close();
		return callList;
	}
}
